import { Button } from 'antd';
import { EditorState, type LexicalEditor } from 'lexical';
import React, { useCallback } from 'react';

import MyModal from '@/components/MyModal';
import { t } from '@/locales/i18n';

import Editor from './Editor';
import { EditorVariableLabelPickerType, EditorVariablePickerType } from './type';
import { editorStateToText } from './utils';

const PromptEditor = ({
  showOpenModal = true,
  variables = [],
  variableLabels = [],
  value,
  onChange,
  onBlur,
  minH,
  maxH,
  maxLength,
  placeholder,
  title,
  bg = 'white',
  tip,
}: {
  showOpenModal?: boolean;
  variables?: EditorVariablePickerType[];
  variableLabels?: EditorVariableLabelPickerType[];
  value?: string;
  onChange?: (text: string) => void;
  onBlur?: (text: string) => void;
  minH?: number;
  maxH?: number;
  maxLength?: number;
  placeholder?: string;
  title?: string;
  bg?: string;
  tip?: string;
}) => {
  // const { isOpen, onOpen, onClose } = useDisclosure();
  // const { t } = useTranslation();
  const [isOpen, setIsOpen] = React.useState(false);

  const onOpen = () => {
    setIsOpen(true);
  };

  const onClose = () => {
    setIsOpen(false);
  };

  const onChangeInput = useCallback(
    (editorState: EditorState, editor: LexicalEditor) => {
      const text = editorStateToText(editor).replaceAll('}}{{', '}} {{');
      onChange?.(text);
    },
    [onChange],
  );
  const onBlurInput = useCallback(
    (editor: LexicalEditor) => {
      const text = editorStateToText(editor).replaceAll('}}{{', '}} {{');
      onBlur?.(text);
    },
    [onBlur],
  );

  return (
    <>
      <Editor
        showOpenModal={showOpenModal}
        onOpenModal={() => {
          onOpen();
        }}
        variables={variables}
        variableLabels={variableLabels}
        minH={minH}
        maxH={maxH}
        maxLength={maxLength}
        value={value}
        onChange={onChangeInput}
        onBlur={onBlurInput}
        placeholder={placeholder}
        bg={bg}
        tip={tip}
      />
      <MyModal isOpen={isOpen} onClose={onClose} iconSrc="edit" title={title} w="full">
        <div>
          <Editor
            minH={400}
            maxH={400}
            maxLength={maxLength}
            showOpenModal={false}
            variables={variables}
            variableLabels={variableLabels}
            value={value}
            onChange={onChangeInput}
            onBlur={onBlurInput}
            placeholder={placeholder}
          />
        </div>
        <div className="ml-auto mt-4">
          <Button type="primary" className="mr-2 px-6" onClick={onClose}>
            {t('common.Confirm')}
          </Button>
        </div>
      </MyModal>
    </>
  );
};
export default React.memo(PromptEditor);
